﻿using OnlineMealOrdering.Models;
using OnlineMealOrdering.Persistence;
using OnlineMealOrdering.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace OnlineMealOrdering.Extends.Attributes
{
    /// <summary>
    /// Based action request to Check user whether is authorized
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
    public class FormAuthorizeAttribute : ActionFilterAttribute
    {
        FilterContextInfo fcinfo;

        public string[] Roles { get; set; }

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            fcinfo = new FilterContextInfo(filterContext);

            bool isLogin = HttpContext.Current.User.Identity.IsAuthenticated;
            if (isLogin)
            {
                //validate authorization
                bool isInRole = false;
                try
                {
                    using (var ctx = new OnlineStoreDbContext())
                    {
                        List<string> userRoles = AccountModel.GetRolesOfUser(((CustomIdentity)(HttpContext.Current.User.Identity)).UserCode);
                        foreach (var role in userRoles)
                        {
                            if (Roles.Contains(role))
                            {
                                isInRole = true;
                                break;
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    //todo: 记录日志
                    filterContext.Result = new ContentResult
                    {
                        Content = "获取您的权限时出错，请稍后再访问。",
                        ContentEncoding = Encoding.UTF8
                    };
                    return;
                }
                if (isInRole)
                {
                    //pass authorize
                }
                else
                { 
                    //has not pass authorize
                    filterContext.Result = new ContentResult
                    {
                        Content = "您未通过授权！访问被拒绝！",
                        ContentEncoding = Encoding.UTF8
                    };
                    //filterContext.Result = new HttpUnauthorizedResult();
                    //filterContext.Result = new RedirectResult("http://www.baidu.com");
                    //filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { Controller = fcinfo.controllerName, action = fcinfo.actionName }));
                }
                
            }
            else
            {
                filterContext.Result = new ContentResult
                {
                    Content = "您未通过身份验证！访问被拒绝！",
                    ContentEncoding = Encoding.UTF8
                };
            }
        }

    }

    /// <summary>
    /// Info of context filter
    /// </summary>
    public class FilterContextInfo
    {
        public FilterContextInfo(ActionExecutingContext filterContext)
        {
            #region 获取链接中的字符
            // 获取域名  
            domainName = filterContext.HttpContext.Request.Url.Authority;
            //获取模块名称    
            module = filterContext.HttpContext.Request.Url.Segments[1].Replace('/', ' ').Trim();
            //获取 controllerName 名称     
            controllerName = filterContext.RouteData.Values["controller"].ToString();
            //获取ACTION 名称        
            actionName = filterContext.RouteData.Values["action"].ToString();
            #endregion
        }

        public string domainName { get; set; }
        public string module { get; set; }
        public string controllerName { get; set; }
        public string actionName { get; set; }
    }
}
